<template>
  <div>
    <ul class="ivr-ul">
      <time-line v-show="getCallHistory.list" v-for="(item, index) in getCallHistory.list" :key="item._id">
        <span class="date">{{item.OFFERING_TIME}}</span>
        <span class="call-type">{{item.STATUS_show}}</span>
        <agent :id="item.DISPOSAL_AGENT" :isNum="true" :isCallDetail="true" class="node-type"></agent>
        <span class="node-type">{{item.queueName}}</span>
        <span class="node-type play-wrap">
           <span class="play" v-show="item.CALL_TIME_LENGTH && isListent" @click.stop="showListentWindow(item.FILE_SERVER, item.RECORD_FILE_NAME, item.STATUS, item.PBX)"><strong></strong></span>
           <span class="time-len">{{item.CALL_TIME_LENGTH_show}}</span>
        </span>
        <span class="query" @click.stop="queryCallHistory(item)">{{$t('call.queryDetail')}}</span>
      </time-line>
    </ul>
    <div class="btn" v-show="!noMore && (getCallHistory.count > 10)" @click.stop="loadMore">{{$t('public.loadMore')}}</div>
    <el-dialog modal-append-to-body lock-scroll top="10%" :title="$t('call.listenAudio')" :visible.sync="listentAudio" @close="closeModal" @open="openModal">
      <old-audio-common v-if="showOld" flagId="call_history_old" :srcUrl="fileServer + '/' + fileName" :refreshAudio="refreshAudio" :pauseAudio="pauseAudio"  :isShowAudioDownload="false" :isShowSubmitAudio="false" :currentObj="{}"></old-audio-common>
      <audio-common v-if="!showOld"  flagId="call_history" @showOldAudio="showOldAudio" callStatus='dealing' :srcUrl="fileServer + '/' + fileName" :refreshAudio="refreshAudio" :pauseAudio="pauseAudio"  :isShowAudioDownload="false" :isShowSubmitAudio="false" :currentObj="{}"></audio-common>
    </el-dialog>
    <el-dialog modal-append-to-body lock-scroll width="800px" top="10%" :title="$t('call.modalCallInfo')" :visible.sync="queryDetail" @close="closeModal('detail')" @open="openModal('detail')">
      <detail-table  :callData="currentCallDetail" audioId="call_history_details" :pauseAudio="pauseAudio"></detail-table>
    </el-dialog>
  </div>
</template>
<script>
  // 此组件是右侧通话详情下面的通话历史
  import TimeLine from '@/components/ui-modules/timeLine/TimeLine'
  import Agent from '@/components/public-modules/cache/Agent'
  import AudioCommon from '@/components/public-modules/audio'
  import OldAudioCommon from '@/components/public-modules/audio/audio.vue'
  import DetailTable from '@/components/public-modules/cust-tab-content/call-detail/DetailTable.vue'
  import { isHasFunc, getCache, getCacheByKey, checkHideTel, getCallTimeLength } from '@/utils/m7Utils.js'
  export default {
    name: 'callHistory',
    data () {
      return {
        showOld: false,
        pauseAudio: 'open',
        isListent: false, // 听取录音的权限
        listentAudio: false, // 是否打开录音弹窗
        fileServer: '', //  url地址
        fileName: '', //  url地址
        refreshAudio: 0, // 是否刷新音频
        queryDetail: false, // 是否查看通话历史详情
        currentCallDetail: {}, // 当前被查看的详情
        noMore: false, // 是否点击加载更多
        page: 1 // 页数
      }
    },
    props: {
      callHistory: {
        type: Object,
        default () {
          return {}
        }
      },
      currentCallData: {
        type: Object,
        default () {
          return {}
        }
      },
      callSheetId: String
    },
    watch: {
      callSheetId () { // 通话id一变就重置
        this.noMore = false
        this.page = 1
      }
    },
    computed: {
      getCallHistory () { // 获取通话历史
        return this.callHistory || {}
      }
    },
    components: {
      TimeLine,
      Agent,
      AudioCommon,
      OldAudioCommon,
      DetailTable
    },
    methods: {
      showOldAudio (curr) {
        this.showOld = curr
      },
      queryCallHistory (obj) {
        // 处理座席
        let agentObj = this.$store.getters.agents[obj.DISPOSAL_AGENT]
        if (agentObj) {
          obj.DISPOSAL_AGENT_show = agentObj.displayName + '[' + agentObj.loginName + ']'
        } else {
          obj.DISPOSAL_AGENT_show = '--'
        }
        // 呼叫类型
        let CONNECT_TYPE = ''
        if (getCacheByKey('callType', 'code_value', obj.CONNECT_TYPE) != null) {
          CONNECT_TYPE = getCacheByKey('callType', 'code_value', obj.CONNECT_TYPE).code_name
        }
        if (obj.CONNECT_TYPE != null) {
          if (obj.CONNECT_TYPE === 'dialout' || obj.CONNECT_TYPE === 'dialTransfer') {
            obj.CALLED_NO_SHOW = checkHideTel(obj.CALLED_NO, this.$store.state.session.user)
            obj.CALL_NO_SHOW = obj.CALL_NO
          } else {
            obj.CALLED_NO_SHOW = obj.CALLED_NO
            obj.CALL_NO_SHOW = checkHideTel(obj.CALL_NO, this.$store.state.session.user)
          }
        }
        obj.CONNECT_TYPE_show = CONNECT_TYPE
        // 满意度
        let appraiseKey = obj.INVESTIGATE ? obj.INVESTIGATE : ''
        let options = this.$getCache('investigate')
        let satisfaction = ''
        for (let i = 0; i < options.length; i++) {
          if (appraiseKey === options[i].value) {
            satisfaction = options[i].name
            break
          }
        }
        if (!satisfaction) {
          satisfaction = appraiseKey || '' // 若字典配置被删除就默认显示数字eg:1
        }
        obj.satisfaction = satisfaction
        obj.CALL_TIME_LENGTH_show = getCallTimeLength(obj.CALL_TIME_LENGTH)
        obj.queueTimeLen = getCallTimeLength(obj.QUEUE_TIME_LENGTH)
        obj.RING_TIME_LENGTH_show = getCallTimeLength(obj.RING_TIME_LENGTH)
        if (obj.MANYQUEUE_NUMBER) {
          let queueArr = obj.MANYQUEUE_NUMBER.split(';')
          let queueArrName = ''
          for (let i = 0; i < queueArr.length; i++) {
            if (i > 0) {
              queueArrName += ' => '
            }
            let queueNameObj = getCacheByKey('queues', 'Exten', queueArr[i])
            if (queueNameObj) {
              queueArrName += queueNameObj.DisplayName
            }
          }
          obj.queueArrName = queueArrName
        } else {
          obj.queueArrName = '--'
        }
        if (obj.REPEAT_CALL) {
          obj.repeatCall = obj.REPEAT_CALL === '48h' ? this.$t('call.repeatCall48h') : this.$t('call.repeatCall24h')
        } else {
          obj.repeatCall = '--'
        }
        this.currentCallDetail = obj
        this.queryDetail = true
      },
      loadMore () { // 点击加载更多
        this.page += 1
        let routes = this.$route.path.split('/')
        let tabType = routes[3]
        let data = {'CALL_NO': this.currentCallData.CALL_NO, 'OFFERING_TIME': this.currentCallData.OFFERING_TIME, 'page': this.page, 'limit': 10}
        let actionData = {'data': data, type: tabType}
        this.$store.dispatch('queryLatestedCallSheet', actionData).then(resp => {
          if (resp && resp.success) {
            let list = resp.list || []
            if (list.length < 10) {
              this.noMore = true
            } else {
              this.noMore = false
            }
          }
        })
      },
      closeModal (flag) { // 关闭弹窗，录音也暂停
        let myAudio = document.getElementById('quality-autoplay_call_history_old')
        if (flag === 'detail') {
          myAudio = document.getElementById('quality-autoplay_call_history_details_old')
        }
        if (myAudio) {
          if (myAudio.currentSrc) {
            myAudio.pause()
          }
        }
        this.pauseAudio = 'close'
      },
      openModal (flag) { // 打开弹窗，开始播放录音
        let myAudio = document.getElementById('quality-autoplay_call_history_old')
        if (flag === 'detail') {
          myAudio = document.getElementById('quality-autoplay_call_history_details_old')
        }
        if (myAudio) {
          if (myAudio.paused) {
            myAudio.currentTime = 0
            if (myAudio.currentSrc) { // url 有地址时
              setTimeout(function () { // 解决.play()被其他请求阻断的问题
                myAudio.play()
              }, 100)
            }
          }
        }
        this.pauseAudio = 'open'
      },
      showListentWindow (server, name, status, pbx) { // 听取录音
        if (server.indexOf('record.7moor.com') > -1 || server.indexOf('m7-record.oss-cn-hangzhou') > -1) {
          server = 'https' + server.substr(server.indexOf(':'), server.length)
          if (status === 'voicemail' || status === 'dealing') { // 只有已接听和已留言才会是有效的录音地址
            this.fileServer = server
            this.fileName = name
          }
          this.listentAudio = true
        } else if (document.location.protocol === 'https:') {
          let self = this
          if (pbx) {
            getCache('accountPbx', pbx, this, function (pbxObj) {
              if (pbxObj) {
                if (pbxObj.assDomain) {
                  let assDomain = pbxObj.assDomain
                  if (assDomain.substr(assDomain.length - 1, assDomain.length) === '/') {
                    assDomain = assDomain.substr(0, assDomain.length - 1)
                  }
                  server = assDomain
                }
              }
              if (status === 'voicemail' || status === 'dealing') { // 只有已接听和已留言才会是有效的录音地址
                self.fileServer = server
                self.fileName = name
              }
              self.listentAudio = true
            })
          } else {
            if (status === 'voicemail' || status === 'dealing') { // 只有已接听和已留言才会是有效的录音地址
              this.fileServer = server
              this.fileName = name
            }
            this.listentAudio = true
          }
        } else {
          if (status === 'voicemail' || status === 'dealing') { // 只有已接听和已留言才会是有效的录音地址
            this.fileServer = server
            this.fileName = name
          }
          this.listentAudio = true
        }
        this.refreshAudio = Math.random()
      }
    },
    beforeMount () {
      if (this.$store.state.session.user.isAdmin || !isHasFunc('func_user_call_sheet_listen_file', this.$store.state.session.user)) {
        this.isListent = true // 是否有听取录音的权限
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .ivr-ul .ui-time-line:before
    top 0
  .node-type, .call-type
    margin 0 10px
    display inline-block
    width 120px
    overflow hidden
    text-overflow ellipsis
    white-space nowrap
    vertical-align bottom
  .call-type
    width 90px
  .date
    margin 0 12px
    color $cf-gray4
    display inline-block
    width 12em
  .time-len
    padding-left 26px
  .play-wrap
    position relative
    height 16px
    width 92px
    .play
      position absolute
      left 0
      top 0
      transform scale(.8)
      width 18px
      height 18px
      border 1px solid $c-main
      margin -2px 8px 0 0
      border-radius 50%
      cursor pointer
      strong
        display inline-block
        width 0
        height 0
        border 4px solid $c-main
        border-color transparent transparent transparent $c-main
        margin 5px 0px 1px 8px
  .query
    color $c-main
    cursor pointer
    display inline-block
  .btn
    cursor pointer
    color $c-main
    margin 20px 0 0 32px
</style>
